#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include "songlrc.h"
extern int chunmusic;

struct lrc *lrclist(struct lrc *head,struct lrc *pnew)//加节点
{
	struct lrc *p = head,*pold = NULL;

	if(head == NULL)
	{
		pnew->next = NULL;
		head = pnew;
	}
	else
	{
		while((pnew->time > p->time) && (p->next != NULL))
		{
			pold = p;
			p = p->next;
		}
		if(pnew->time <= p->time)
		{
			if(p == head)
			{
				pnew->next = head;
				head = pnew;
			}
			else
			{
				pold->next = pnew;
				pnew->next = p;
			}
		} 
		else
		{
			p->next = pnew;
			pnew->next = NULL;
		}
	}
	//printf("%s\n",head->lrctext);
	return head;
}

struct lrc *GetLrc(char *lrcpath) //形成歌词链表，返回链头
{
	FILE *fd;
	int size,rsize;
	char *buf = NULL;
	//struct lrc *head;
	fd = fopen(lrcpath,"r");
	/*if(strcmp(lrcpath,"/home/hhb/Music/CapoProductions-Journey.lrc") == 0)
	{
		printf("本首歌曲为纯音乐，请欣赏\n");
		return NULL;
	}*/
	if(fd == NULL)
	{
		printf("本首歌曲为纯音乐，请欣赏\n");
		chunmusic = 1;
		return NULL;
	}

	fseek(fd,0,2); //文件描述符偏移到文件尾
	size = ftell(fd); //计算文件大小（当前文件描述符到文件头的字节数）
	rewind(fd);
	//printf("%d\n",size);
	buf = (char *)malloc(size + 1);
	rsize = fread(buf,1,size,fd); //注意fread返回值为真是读取的项数，所以我们一个一个的读，读size次，读到buf里
	fclose(fd);
	*(buf + rsize) = '\0';  //将最后一位置成'\0'
	//printf("%d\n",rsize);
	//printf("%s\n",buf);     //现在buf里就是lrc文件的内容

	char *pb = NULL,*head = NULL,*mid = NULL;  //pb去遍历，head指向buf的头,mid用来指向一行的歌词信息
	struct lrc *pnew = NULL;
	char temp[200] = {0};
	int i = 0,j = 0;
	int count = 0;

	struct lrc *lrchead = NULL;
	//lrchead = (struct lrc*)malloc(sizeof(struct lrc));

	head = pb = buf;
	int a = 1;
	while((pb - head) != size)
	{
		while( *pb != '\n')
		{
			temp[i] = *pb;
			pb++;
			i++;
		}
		temp[i] = '\0';   //temp储存一行的歌词信息
		//printf("%s\n",temp);
		pb++;
		mid = temp;
		for(j=0;j<i;j++)
		{
			if(temp[j] == '.')  //统计此行歌词出现的次数
			{
				count++;
			}
		}
		//printf("%d\n",count);
		pnew = (struct lrc*)malloc(sizeof(struct lrc));
		strcpy(pnew->lrctext,mid+count*11);
		//printf("%s\n",pnew->lrctext);
		pnew->time = atoi(mid+1)*60+atoi(mid+4);
		pnew->next = NULL;
		if(a == 1)
		{
			lrchead = pnew;
			a++;
		}
		else
		{
			lrclist(lrchead,pnew);
		}	

		while(count > 1)  //当某行歌词出现多次，按不同时间点加入链表
		{
			pnew = (struct lrc*)malloc(sizeof(struct lrc));
			strcpy(pnew->lrctext,mid+count*11);
			pnew->time = atoi(mid+11*(count-1)+1)*60+atoi(mid+11*(count-1)+4);
			lrclist(lrchead,pnew);
			count--;
		}
		memset(temp,0,200);
		i = 0;
		count = 0;
	}

	return lrchead;
}

